import styles from './Table.module.scss'
import Detail from './Detail'
import Dialog from '@renderer/components/dialog'

import { dateFormat } from '@renderer/utils/utils'
import { getMakeGroupFriendList, pauseMakeGroupFriend, startMakeGroupFriend, delMakeGroupFriend } from '@renderer/ajax/api/addGroupBuddy'
import { ElTable, ElTableColumn, ElPagination, ElEmpty, ElMessage, ElButton, ElProgress, ElTooltip, ElPopover, ElTag } from 'element-plus'
import { reactive, ref, defineComponent, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
    name: 'AddGroupBuddyTable',
    props: {
        fetchParams: {
            type: Object,
            default: () => ({})
        }
    },
    setup(props, { emit, slots }) {
        const router = useRouter()
        const state = reactive({
            list: [],
            total: 0,
            page: 1,
            page_size: 15,
            id: '',
            type: 0,
            message: ''
        })
        const DialogData = reactive({
            visible: false,
            width: '500px',
            title: '',
            content: '',
            footer: ['取消', '确定', 'center']
        })
        const DetailRef = ref<any>(null)
        const getData = async () => {
            let params = {
                ...props.fetchParams,
                Page: state.page || 1,
                PageSize: state.page_size || 15
            }

            const res = await getMakeGroupFriendList(params)
            const { data, total } = res || {}
            state.list = data || []
            state.total = total || 0
        }

        // 定时器5秒自动刷新页面，离开页面销毁
        let timer: any = null
        onMounted(() => {
            timer = setInterval(() => {
                getData()
            }, 5000)
        })
        onUnmounted(() => {
            clearInterval(timer)
        })
        watch(
            () => props.fetchParams,
            () => {
                getData()
            },
            { deep: true, immediate: true }
        )
        const onMessage = () => ElMessage.success(state.message)
        const onSubmit = async () => {
            // 0 暂停 1 开始  2 删除
            state.type == 0 && (await pauseMakeGroupFriend({ Id: state.id }))
            state.type == 1 && (await startMakeGroupFriend({ Id: state.id }))
            state.type == 2 && (await delMakeGroupFriend({ Id: state.id }))
            state.type == 2 && (state.page = (state.total - 1) % state.page_size === 0 ? state.page-- : state.page)
            getData()
            onMessage()
            DialogData.visible = false
        }
        const onBegin = (row: any) => {
            DialogData.title = '开始任务'
            DialogData.content = '确定开始所选任务吗？'
            state.message = '开始任务成功'
            state.type = 1
            state.id = row.id
            DialogData.visible = true
        }
        const onPaused = (row: any) => {
            DialogData.title = '暂停任务'
            DialogData.content = '确定暂停所选任务吗？'
            state.message = '暂停任务成功'
            state.type = 0
            state.id = row.id
            DialogData.visible = true
        }
        const onDel = (row: any) => {
            DialogData.title = '删除任务'
            DialogData.content = '确定删除所选内容吗？（进行中、已暂停的任务删除后将终止任务）'
            state.message = '删除任务成功'
            state.type = 2
            state.id = row.id
            DialogData.visible = true
            // state.page = (state.total - 1) % state.page_size === 0 ? state.page-- : state.page
            getData()
        }
        const onLook = (row: any) => {
            DetailRef.value.onState(row)
        }
        const onSizeChange = (v: number) => {
            state.page_size = v
        }
        const onCurrentChange = (v: number) => {
            state.page = v
        }
        // 渲染群聊
        const renderGroup = (row: any) => {
            const allNum = row.allGroupChatNum > 20 ? `等共${row.allGroupChatNum }个群` : ''
            const groupNameContent = `${row.groupChatList.map(item => item.Name).join('、')}${allNum}`
            const renderTooltip = (
                <ElTooltip effect="dark" popperStyle={{
                    maxWidth: '560px',
                }} content={groupNameContent} showAfter={800} placement="top" disabled={groupNameContent.length < 13}>
                    {row.isAllGroupChat ? <div class={styles.group_list}>全部群聊({row.allGroupChatNum ?? ''}个)</div> : <div class={styles.group_list}>{groupNameContent}</div>}
                </ElTooltip>
            )
            return renderTooltip
        }
        // 渲染标签
        const renderTags = (row: any) => {
            const popoverTag = (
                <ElPopover
                    placement="top"
                    width={300}
                    trigger="hover"
                    showAfter={800}
                    popperStyle={{
                        maxHeight: '300px',
                    }}
                    vSlots={{
                        reference: () => (
                            <div class={styles.tag_list}>
                                {row.tagList.map((item) => (
                                    <ElTag class={styles.tag} type={item.isDelete ? 'info' : ''} key={item.id}>
                                        {item.name}
                                    </ElTag>
                                ))}
                            </div>
                        ),
                        default: () => (
                            <div>
                                {row.tagList.map((item) => (
                                    <ElTag class={styles.hover_tag} type={item.isDelete ? 'info' : ''} key={item.id}>
                                        {item.name}
                                    </ElTag>
                                ))}
                            </div>
                        )
                    }}
                />
            )
            return row.tagList?.length ? popoverTag : '--'
        }
        // 渲染空状态
        const renderEmpty = () => (
            <ElEmpty
                vSlots={{
                    description: () => (
                        <div class="empty">
                            <p>当前没有正在执行的任务</p>
                            <p>支持输入手机号自动添加好友，为避免风险</p>
                            <p>请自行设置每日添加数量上限</p>
                        </div>
                    )
                }}
            />
        )
        // 渲染当前状态
        const renderStatus = (row) => {
            const text = ['', '未开始', '进行中', '已暂停', '已完成']
            const color = ['', '#686e71', '#4d9ef8', '#eb5851', '#5fcb71']
            const jindu = row.completed ? ((row.completed / row.total) * 100).toFixed(2) : 0
            return (
                <div class={styles.status}>
                    <div class={styles.status_name}> {text[row.status]}</div>
                    <ElProgress class={styles.progress} text-inside={true} stroke-width={15} percentage={jindu} color={color[row.status]} />
                    <div>
                        {row.completed}/{row.total}
                    </div>
                </div>
            )
        }
        // 渲染操作按钮
        const renderBtn = (row) => {
            const BEGIN = (
                <ElButton size="small" onClick={() => onBegin(row)}>
                    开始任务
                </ElButton>
            )
            const PAUSED = (
                <ElButton size="small" onClick={() => onPaused(row)}>
                    暂停任务
                </ElButton>
            )
            const arr = ['', BEGIN, PAUSED, BEGIN]
            return (
                <>
                    {arr[row.status]}
                    {row.status == 1 ?
                        <ElButton size="small" onClick={() => router.push({ path: '/publishGroupNotice/create', query: { id: row.Id } })}>
                            编辑
                        </ElButton>
                        : ''
                    }

                    <ElButton size="small" onClick={() => onLook(row)}>
                        查看详情
                    </ElButton>
                    <ElButton size="small" onClick={() => onDel(row)}>
                        删除
                    </ElButton>
                </>
            )
        }

        return () => (
            <>
                <ElTable data={state.list}  height="calc(100vh - 380px)"  vSlots={{ empty: () => renderEmpty() }}>
                    <ElTableColumn label="任务标题" prop="title" width="260" />
                    <ElTableColumn label="所选群聊" min-width="200" vSlots={{ default: ({ row }) => renderGroup(row) }} />
                    <ElTableColumn label="客户标签" prop="name" min-width="200" vSlots={{ default: ({ row }) => renderTags(row) }} />
                    <ElTableColumn label="创建时间" width="220" vSlots={{ default: ({ row }) => row.createdAt }} />
                    <ElTableColumn label="任务状态" min-width="300" vSlots={{ default: ({ row }) => renderStatus(row) }} />
                    <ElTableColumn label="操作" fixed="right" width="300" vSlots={{ default: ({ row }) => renderBtn(row) }} />
                </ElTable>
                <ElPagination
                    class={styles.pagination}
                    vModel:currentPage={state.page}
                    vModel:pageSize={state.page_size}
                    page-sizes={[15, 30, 50, 100]}
                    background
                    layout="total,  prev, pager, next,sizes, jumper"
                    total={state.total}
                    onSizeChange={onSizeChange}
                    onCurrentChange={onCurrentChange}
                />
                <Detail ref={DetailRef} />
                <Dialog state={DialogData} onCancel={() => (DialogData.visible = false)} onConfirm={onSubmit} />
            </>
        )
    }
})
